﻿/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Nvigorate.Aspect;
using Nvigorate.Common;
using Nvigorate.Common.Reflection;
using Nvigorate.Extensions;
using Nvigorate.Relational.Mapping;
using Nvigorate.Relational.Mapping.Index;
using Nvigorate.Relational.Mapping.Interface;
using Nvigorate.Relational.Navigation;
using Nvigorate.Relational.Visitors;

namespace Nvigorate.Relational.Repository
{
    public class NavigatingPersistable : INavigatingPersistable
    {
        #region Fields

        private readonly IPersistable _instance;
        private readonly IRepositoryMapIndex _repositoryMapIndex;
        protected List<Tuple<ITargetRelationship, IPersistable>> _relatives = new List<Tuple<ITargetRelationship, IPersistable>>();

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;
        public event PropertyChangingEventHandler PropertyChanging;

        #region Constructors
        
        public NavigatingPersistable(IPersistable persistable, IRepositoryMapIndex repositoryMapIndex)
        {
            _instance = persistable;
            _repositoryMapIndex = repositoryMapIndex;
        }

        #endregion

        #region Properties

        public List<Tuple<ITargetRelationship, IPersistable>> Relatives
        {
            get { return _relatives; }
        }

        private IPersistableVisitor Visitor{get; set;}
        
        #endregion

        #region IPersistable Interface

        public List<Tuple<string, object>> ChangedValues
        {
            get { return _instance.ChangedValues; }
            set { _instance.ChangedValues = value; }
        }

        public bool IsDirty
        {
            get { return _instance.IsDirty; }
        }

        public bool IsNew
        {
            get { return _instance.IsNew; }
        }

        public List<string> Keys
        {
            get { return _instance.Keys; }
            set { _instance.Keys = value; }
        }

        public List<string> Loaded
        {
            get { return _instance.Loaded; }
            set { _instance.Loaded = value; }
        }

        public bool RelationshipChanged
        {
            get { return _instance.RelationshipChanged; }
            set { _instance.RelationshipChanged = value; }
        }

        public string RepositoryName
        {
            get { return _instance.RepositoryName; }
            set { _instance.RepositoryName = value; }
        }

        public void AddChangedValue(string changedPropertyName, object originalValue)
        {
            _instance.AddChangedValue(changedPropertyName, originalValue);
        }

        public object GetOriginalValue(string propertyName, object instance)
        {
            return _instance.GetOriginalValue(propertyName, instance);
        }

        public Guid GetRelativeTicket(Type relativeType, string foreignKeyProperty)
        {
            var parent = _relatives
                .FirstOrDefault(p =>
                {
                    if (p.Value1 is OneToManyRelationship)
                    {
                        var oneToMany = p.Value1 as OneToManyRelationship;
                        return (oneToMany.Constraints.ContainsValue(foreignKeyProperty) && oneToMany.RelativeType == relativeType) ||
                               (oneToMany.Constraints.ContainsKey(foreignKeyProperty) && oneToMany.SubjectType == relativeType);
                    }
                    else
                    {
                        return false;
                    }
                });

            return parent == null ? PersistenceTicket : parent.Value2.PersistenceTicket;
        }

        public void ClearDirtyState()
        {
            _instance.ClearDirtyState();
        }

        public void ForceInsert()
        {
            _instance.ForceInsert();
        }

        public Guid PersistenceTicket
        {
            get { return _instance.PersistenceTicket; }
        }

        public object Instance
        {
            get { return _instance.Instance; }
            set { _instance.Instance = value; }
        }

        public Type InstanceType
        {
            get { return _instance.InstanceType; }
        }

        [ForbidLazyLoadingAspect]
        public void Accept(IPersistableVisitor visitor, IPersistable parent)
        {
            if (visitor.Visited(this))
                return;

            Visitor = visitor;

            if (visitor.Direction == TraversalDirection.DepthFirst)
            {
                TraverseDepthFirst(this, parent);
                return;
            }
            else if(visitor.Direction == TraversalDirection.BreadthFirst)
            {
                TraverseBreadthFirst(this, parent);
            }
            else
            {
                Visitor.Visit(this, parent);
            }
        }

        [ForbidLazyLoadingAspect]
        public void Accept(IPersistableVisitor visitor)
        {
            Accept(visitor, null);
        }
        
        #endregion

        #region Private Methods

        private void PassVisitorToChild(object child, ITargetRelationship relationship)
        {
            if (_repositoryMapIndex.HasMap(child.GetType()))
            {
                var persistable = PersistenceDecorator.Create(child);
                var navigator = persistable.GetNavigator(_repositoryMapIndex);
                navigator.Relatives.Add(Tuple.Create(relationship, this as IPersistable));
                _relatives.Add(Tuple.Create(relationship, navigator as IPersistable));
                navigator.Accept(Visitor, this);
            }
        }

        public void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

        public void RaisePropertyChanging(string property)
        {
            if (PropertyChanged != null)
                PropertyChanging(this, new PropertyChangingEventArgs(property));
        }

        #endregion

        #region Traversal Methods

        private void TraverseBreadthFirst(IPersistable instance, IPersistable parent)
        {
            var map = _repositoryMapIndex.GetMap(instance.InstanceType);

            var relationships = map.Relationships.OfType<OneToManyRelationship>();
            var dependencyRelationships = relationships
                .Where(r => r.Relationship == Relationship.Child || r.Relationship == Relationship.Pair);

            ProcessRelatives(instance, dependencyRelationships.Where(RelativeHasKey).Cast<ITargetRelationship>());

            Visitor.Visit(instance, parent);

            ProcessRelatives(instance, relationships.Where(r => !RelativeHasKey(r)).Cast<ITargetRelationship>());

            var manyToMany = map.Relationships.OfType<ManyToManyRelationship>().Cast<ITargetRelationship>();
            ProcessRelatives(instance, manyToMany);

            var secondPassDependencies =
                relationships
                    .Where(r => r.Relationship == Relationship.Parent)
                    .Where(RelativeHasKey);

            ProcessRelatives(instance, secondPassDependencies.Cast<ITargetRelationship>());
        }

        private void TraverseDepthFirst(IPersistable instance, IPersistable parent)
        {
            var map = _repositoryMapIndex.GetMap(instance.InstanceType);

            var relationships = map.Relationships.OfType<OneToManyRelationship>();
            var dependencyRelationships = relationships
                .Where(r => r.Relationship == Relationship.Child || r.Relationship == Relationship.Pair);

            ProcessRelatives(instance, relationships.Where(r => !RelativeHasKey(r)).Cast<ITargetRelationship>());

            Visitor.Visit(instance, parent);

            ProcessRelatives(instance, dependencyRelationships.Where(RelativeHasKey).Cast<ITargetRelationship>());

            var manyToMany = map.Relationships.OfType<ManyToManyRelationship>().Cast<ITargetRelationship>();
            ProcessRelatives(instance, manyToMany);

            var secondPassDependencies =
                relationships
                    .Where(r => r.Relationship == Relationship.Parent)
                    .Where(RelativeHasKey);

            ProcessRelatives(instance, secondPassDependencies.Cast<ITargetRelationship>());
        }

        private void ProcessRelatives(IPersistable instance, IEnumerable<ITargetRelationship> relationships)
        {
            foreach (var relationship in relationships)
            {
                var propertyValue = Reflector.Read(instance.Instance, relationship.RelativeProperty);
                if(propertyValue != null)
                {
                    if (Reflector.IsEnumerable(propertyValue.GetType()))
                    {
                        (propertyValue as IEnumerable).Cast<object>().ForEach(i => PassVisitorToChild(i, relationship));
                    }
                    else
                    {
                        PassVisitorToChild(propertyValue, relationship);
                    }
                }
            }
        }

        public bool RelativeHasKey(OneToManyRelationship relationship)
        {
            var map = _repositoryMapIndex.GetMap(relationship.RelativeType);
            if(map == null)
                return false;

            return relationship
                .Constraints
                .Values
                .Any(p =>
                    map.GetAssignmentsByPredicate(a => a.Target.Field == p && a.PrimaryKey).Count() > 0);
        }

        #endregion
    }
}